<template>
  <view class="body">
    <view class="progress">
      <view v-if="state.questionList.length > 0" class="model-name">
        {{ state.questionList[state.tabActive].name }}
      </view>
      <up-line-progress
        :percentage="100 * (current / total) || 0"
        activeColor="#00d1b6"
        inactiveColor="#f5f5f5"
        :showText="false"
        height="8"
      ></up-line-progress>
    </view>
    <view v-if="state.isSelect" class="wrap">
      <view class="tips">请根据实际情况，选择最符合的一项</view>
      <view class="questionName">请选择体检用户</view>
      <view
        v-if="state.userList.length > 0"
        class="selects"
        style="max-height: calc(100vh - 576rpx); overflow: auto"
      >
        <view
          v-for="(item, index) of state.userList"
          :key="index"
          @tap="selectUser(item)"
          :class="['items', item.check ? 'active' : '']"
        >
          <view class="item-name">{{ item.patName }}</view>
          <view class="info-tag">{{ item.gender }} | {{ item.age }}岁</view>
        </view>
      </view>
    </view>
    <view v-if="!state.isSelect && state.questionList.length > 0" class="wrap">
      <scroll-view :scroll-top="scrollTop" @scroll="scroll" class="scroll-Y" scroll-y="true">
        <view class="tips">请根据实际情况，选择最符合的一项</view>
        <my-question
          style="margin-top: 32rpx"
          :cId="cId"
          :cWidth="cWidth"
          :List="state.questionList[Number(state.tabActive)]?.list"
          @change="onChange"
        />
      </scroll-view>
      <scroll-view
        :scroll-top="scrollTop"
        @scroll="scroll"
        class="scroll-Y"
        scroll-y="true"
        v-if="false"
      >
        <view class="tips">请根据实际情况，选择最符合的一项</view>
        <view class="questionName">
          {{ state.questionList[state.tabActive].list[state.questionActive].questionName }}
          <view
            v-if="
              state.questionList[state.tabActive].list[state.questionActive].questionType == '多选'
            "
            class="tag"
            >多选</view
          >
        </view>
        <view
          v-if="
            (state.questionList[state.tabActive].list[state.questionActive].exc &&
              state.questionList[state.tabActive].list[state.questionActive].exc == 'pain') ||
            state.questionList[state.tabActive].list[state.questionActive].exc == 'knee-pain'
          "
          class="tips"
          >0-10 (无痛-剧痛)</view
        >
        <view
          class="selects"
          v-if="
            (state.questionList[state.tabActive].list.length > 0 &&
              state.questionList[state.tabActive].list[state.questionActive].questionType ==
                '单选') ||
            state.questionList[state.tabActive].list[state.questionActive].questionType == '多选'
          "
        >
          <view
            v-for="(item, index) of state.questionList[state.tabActive].list[state.questionActive]
              .options"
            :key="index"
            @tap="select(item)"
            :class="[
              'items',
              state.questionList[state.tabActive].list[state.questionActive].sort.includes(
                item.sort
              )
                ? 'active'
                : ''
            ]"
          >
            <view class="item-title">{{ item.value }}</view>
          </view>
        </view>
      </scroll-view>
      <view
        v-if="
          state.questionList[state.tabActive].list.length > 0 &&
          state.questionList[state.tabActive].list[state.questionActive].questionType == '输入'
        "
      >
        <input
          :type="
            state.questionList[state.tabActive].list[state.questionActive].id == 'F-6'
              ? 'text'
              : 'number'
          "
          class="type_input"
          style="font-size: 36rpx"
          v-model="state.questionList[state.tabActive].list[state.questionActive].inputText"
        />
      </view>
      <view
        v-if="
          state.questionList[state.tabActive].list.length > 0 &&
          state.questionList[state.tabActive].list[state.questionActive].questionType == '搜索输入'
        "
      >
        <view @tap="searchShow = true" class="search-input">
          <up-icon name="search" color="#000" size="28" />
          搜索过敏和禁忌食物
        </view>
        <view class="allergy-foods">
          <view class="food-list">
            <view v-for="(item, index) of state.searchResults" :key="index" class="foods-item">
              {{ item }}
              <text @tap="removeFood(item)" style="padding: 0 4rpx; font-size: 36rpx">×</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <up-popup :show="searchShow" mode="bottom" :round="16" closeable @close="searchShow = false">
      <view class="search-body">
        <view class="title">搜索并选择</view>
        <view class="search-bar">
          <up-search
            v-model="state.searchValue"
            @custom="cancelSearch"
            @focus="state.searchFocus = true"
            @change="searchFood"
            :show-action="true"
            @clear="
              () => {
                state.isSearch = false
                state.searchList = []
              }
            "
            actionText="取消"
            placeholder="搜索过敏和禁忌食物"
          />
        </view>
        <!-- <uni-search-bar
          v-model="state.searchValue"
          @cancel="cancelSearch"
          @focus="state.searchFocus = true"
          @input="searchFood"
          @clear="
            () => {
              state.isSearch = false
              state.searchList = []
            }
          "
          cancelButton="always"
          placeholder="搜索过敏和禁忌食物"
        /> -->
        <!-- 搜索内容 -->
        <view v-if="state.searchFocus" class="search_content">
          <view v-if="state.searchHistory.length > 0 && !state.isSearch" class="search_history">
            <view class="history_top">
              <view class="title">搜索记录</view>
              <icon type="" @tap="clearSearchHistory" class="iconfont icon-shanchu1 img_del" />
            </view>
            <view class="history_content">
              <view
                class="history_item"
                v-for="(item, index) in state.searchHistory"
                :key="index"
                @tap="historySelect(item)"
              >
                {{ item }}
              </view>
            </view>
          </view>
          <view v-if="state.searchList.length === 0 && state.isSearch" class="nodata">
            <image
              class="img_nodata"
              src="https://ainengli.meilianshuke.com/jkhx/noSearchData.png"
            />
            <view class="nodata_text">暂无数据，换个搜索条件试试?</view>
          </view>
          <scroll-view scroll-y="true" class="scroll_view_style">
            <view class="search_list">
              <view
                class="search_item"
                v-for="(item, index) in state.searchList"
                :key="index"
                @tap="selectFoods(item)"
              >
                <view class="name">{{ item.dietName }}</view>
                <image
                  v-if="item.checked"
                  class="img_right"
                  src="https://ainengli.meilianshuke.com/jkhx/common/checkbox-active.png"
                />
                <image
                  v-if="!item.checked"
                  class="img_right"
                  src="https://ainengli.meilianshuke.com/jkhx/common/checkbox.png"
                />
              </view>
            </view>
          </scroll-view>
        </view>
        <view class="fixed">
          <button @tap="searchConfirm" class="next_btn popbtn">确定</button>
        </view>
      </view>
    </up-popup>
    <view class="fixed">
      <button
        v-if="
          state.tabActive != 0 ||
          (state.questionActive != 0 && state.tabActive == 0 && state.questionActive > 3)
        "
        class="pre_btn"
        @tap="prev()"
      >
        上一题
      </button>
      <button class="next_btn" @tap="next()">
        {{
          state.tabActive + 1 == state.questionList.length &&
          state.questionActive + 1 == state.questionList[state.tabActive].list.length
            ? '提交问卷'
            : '下一题'
        }}
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, computed, nextTick, watch } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { debounce, throttle, deepCopy, parseTime, typeOf } from '@/utils/tools'
import { query_patient } from '@/api/family'
import { base_info } from '@/api/moreMessage'
import { search_food } from '@/api/food'
import { get_new_weight, hasSportsPlan } from '@/module/api/sports'
import { new_question, weight_save, question_rewrite } from '@/module/api/questionaire'
import { info_question } from '@/api/questionaire'
import { formatDate } from '@/utils/util'
import store from '@/store'
import MyQuestion from '@/module/components/MyQuestion/single.vue'
import {
  showCondition,
  next,
  validate,
  convert,
  fillValue
} from '@/module/components/MyQuestion/tools'
const cWidth = ref(uni.upx2px(750 - 128))

const state = reactive({
  tabActive: 0, // 模块下标
  questionActive: 3, // 题目下标
  isSelect: false,
  userList: [],
  questionList: [],
  questionInfo: {},
  searchFocus: false,
  isSearch: false,
  searchValue: '',
  searchHistory: [],
  searchList: [],
  searchResults: []
})
const userInfo = ref({})
const chooseInfo = ref({})
const originList = ref([])
const searchShow = ref(false)
const cId = ref('')
const listOld = ref([])

let currentId = ''
const scrollTop = ref(0)
const oldScrollTop = ref(0)

const total = computed(() => {
  let num = 0
  state.questionList.forEach((item: any) => {
    item.list.forEach((val: any) => {
      num++
    })
  })
  return num
})

const current = computed(() => {
  let num = 0
  state.questionList.forEach((item: any, index: number) => {
    item.list.forEach((val: any, idx: number) => {
      if ((index == 0 && idx > 2) || index > 0) {
        if (val.value != '' || val.inputText != '' || val.value.length > 0) {
          num++
        }
      }
    })
  })
  return num
})

onShow(() => {
  //     userInfo.value = JSON.parse(uni.getStorageSync('userInfo'))
  //   chooseInfo.value = userInfo.value.patientInfo
  //   if (!currentId || currentId !== userInfo.value.patientInfo.empi) {
  //     currentId = deepCopy(userInfo.value.patientInfo.empi)
  //     // currentId = '74567895'
  //     init()
  //   }
})

onLoad(() => {
  wx.enableAlertBeforeUnload({
    message: '确认要退出吗？您填写的内容未提交',
    success: function (res) {
      console.log('成功', res)
    },
    fail: function (errMsg) {
      console.log('失败', errMsg)
    }
  })
  userInfo.value = JSON.parse(uni.getStorageSync('userInfo'))
  chooseInfo.value = userInfo.value.patientInfo
  if (!currentId || currentId !== userInfo.value.patientInfo.empi) {
    currentId = deepCopy(userInfo.value.patientInfo.empi)
    // currentId = '74567895'
    init()
  }
})

watch(
  () => state.questionActive,
  () => {
    scrollTop.value = oldScrollTop.value
    nextTick(() => {
      scrollTop.value = 0
    })
  }
)

const getUserList = () => {
  query_patient(userInfo.value.userId).then((res) => {
    state.userList = res.data
    state.userList.forEach((item) => {
      item.check = false
    })
  })
}

const init = async () => {
  //   let params = {
  //     clientId: 3,
  //     empi: userInfo.value.patientInfo.empi
  //   }
  //   new_question(params).then((res) => {
  //     console.log(res.data)
  //     originList.value = JSON.parse(res.data.content)
  //     console.log(originList.value)
  //     const convertList = convert(originList.value)
  //     listOld.value = convertList
  //     console.log(13)
  //     console.log(originList.value)
  //     state.questionList = showCondition(convertList)
  //     // state.questionList[0].list[0].inputText = chooseInfo.value.patName
  //     // state.questionList[0].list[2].inputText = chooseInfo.value.age
  //     // state.questionList[0].list[1].inputText = chooseInfo.value.gender
  //     // console.log('题目列表', originList.value, state.questionList)
  //     //cId.value = state.questionList[0].list[0].id
  //     // state.questionInfo = res.data
  //     // getWeight()
  //   })
  let params = {
    clientId: 11,
    empi: userInfo.value.patientInfo.empi
  }
  info_question(params).then((res) => {
    originList.value = JSON.parse(res.data.content)
    originList.value.forEach((item: any) => {
      item.isFinish = false
    })
    let convertList = convert(originList.value)
    console.log(convertList)

    // listOld.value = convertList
    // console.log(convertList[0])
    state.questionList = showCondition(convertList)
    // listOld.value = state.questionList
    // const leng = state.questionList.length
    // questionListAfter.value = state.questionList[leng - 1].list.slice(-3)
    cId.value = state.questionList[0].list[0].id
    state.questionInfo = res.data
  })
}

// 获取体重
const getWeight = () => {
  get_new_weight({ empi: userInfo.value.patientInfo.empi }).then((res) => {
    if (res.data) {
      state.questionList[0].list[4].inputText = res.data[0].itemValue
      state.questionList[0].list[3].inputText = res.data[1].itemValue
    }
  })
}

const selectUser = throttle((item: any) => {
  // 选择用户
  chooseInfo.value = item
  let params = {
    userId: userInfo.value.userId,
    empi: item.empi
  }
  uni.setStorageSync('questionUserInfo', JSON.stringify(item))
  base_info(params).then((res) => {
    userInfo.value.patientInfo = res.data
    store.commit('SET_USERINFO', info)
    store.dispatch('app/IM_DESTROY')
  })
  item.check = !item.check
  state.questionList[0].list[0].inputText = item.patName
  state.questionList[0].list[2].inputText = item.age
  state.questionList[0].list[1].inputText = item.gender
  setTimeout(() => {
    state.isSelect = false
    state.questionActive += 3
    getRewrite()
  }, 300)
}, 300)

const getRewrite = () => {
  question_rewrite({ clientId: 3, empi: chooseInfo.value.empi }).then((res) => {
    // 填过问卷的就诊人回显问卷
    if (res && res.data) {
      let answer = res.data.patientQuestionnaireAnswerVO
      originList.value.forEach((item) => {
        item.list.forEach((val: any) => {
          if (answer.filter((anw: any) => anw.questionId == val.id).length > 0) {
            if (val.questionType == '单选' || val.questionType == '多选') {
              if (val.questionType == '多选') {
                let arr = <any>[]
                let sortList = answer.filter((anw: any) => anw.questionId == val.id)
                sortList.forEach((i: any) => {
                  val.sort.push(val.options.filter((v: any) => v.id == i.optionId)[0].sort)
                  val.value.push(val.options.filter((v: any) => v.id == i.optionId)[0].value)
                  arr.push(i.optionId)
                })
                val.option = arr.join(',')
              } else {
                val.sort = val.options.filter(
                  (v: any) =>
                    v.id == answer.filter((anw: any) => anw.questionId == val.id)[0].optionId
                )[0].sort
                val.option = answer.filter((anw: any) => anw.questionId == val.id)[0].optionId
                val.value = answer.filter((anw: any) => anw.questionId == val.id)[0].content
              }
            } else if (val.questionType == '输入') {
              val.inputText = answer.filter((anw: any) => anw.questionId == val.id)[0].content
            }
          }
        })
      })
      console.log('问卷回填', answer, state.questionList)
    }
  })
}

const showCondition = (arr) => {
  // console.log('传入的列表', arr)
  const obj = {}
  arr.map((v) => {
    v.list.map((u) => {
      obj[u.id] = u
    })
  })

  let List = []

  arr.map((v) => {
    const L = v.list.filter((u) => {
      if (!u.showCondition) {
        return true
      }
      let show = true
      if (u.showCondition.hasOwnProperty('show')) {
        show = u.showCondition.show
      }
      const r = loop(u.showCondition, obj)
      if (show) {
        return r
      } else {
        return !r
      }
    })
    if (L.length) {
      List.push({
        ...v,
        list: L
      })
    }
  })

  return List
}

const loop = (obj, d) => {
  if (obj.operator === 'AND') {
    return obj.conditions.every((v) => {
      if (v.operator !== 'AND' && v.operator !== 'OR') {
        if (v.operator === '填写完成') {
          return d[v.id].value.trim() !== ''
        } else {
          if (d[v.id].questionType.includes('单选')) {
            return d[v.id].sort == v.value
          } else if (d[v.id].questionType.includes('多选')) {
            return d[v.id].sort.includes(v.value)
          } else if (d[v.id].questionType === '数字选择') {
            return inputTest(v, d[v.id].inputText)
          } else if (d[v.id].questionType === '输入') {
            return inputTest(v, d[v.id].inputText)
          }
          if (typeOf(d[v.id].value) === 'string') {
            return d[v.id].value.trim() !== ''
          } else if (typeOf(d[v.id].value) === 'array') {
            return d[v.id].value.length > 0
          } else {
            return true
          }
          // return f(d[v.id].value)
        }
      } else {
        return loop(v, d)
      }
    })
  } else if (obj.operator === 'OR') {
    return obj.conditions.some((v) => {
      if (v.operator !== 'AND' && v.operator !== 'OR') {
        if (v.operator === '填写完成') {
          return d[v.id].value.trim() !== ''
        } else {
          if (d[v.id].questionType.includes('单选')) {
            return d[v.id].sort == v.value
          } else if (d[v.id].questionType.includes('多选')) {
            return d[v.id].sort.includes(v.value)
          } else if (d[v.id].questionType === '数字选择') {
            return inputTest(v, d[v.id].inputText)
          } else if (d[v.id].questionType === '输入') {
            return inputTest(v, d[v.id].inputText)
          }
          if (typeOf(d[v.id].value) === 'string') {
            return d[v.id].value.trim() !== ''
          } else if (typeOf(d[v.id].value) === 'array') {
            return d[v.id].value.length > 0
          } else {
            return true
          }
          // return f(d[v.id].value)
        }
      } else {
        return loop(v, d)
      }
    })
  }
  return true
}

const select = throttle((item: any) => {
  let currentQuestion = state.questionList[state.tabActive].list[state.questionActive]
  if (currentQuestion.questionType == '单选') {
    // 单选情况
    state.questionList[state.tabActive].list[state.questionActive].value = item.value
    state.questionList[state.tabActive].list[state.questionActive].sort = item.sort
    state.questionList[state.tabActive].list[state.questionActive].option = item.id.toString()
    // if (
    //   state.tabActive + 1 != state.questionList.length ||
    //   state.questionActive + 1 != state.questionList[state.questionList.length - 1].list.length
    // ) {
    //   setTimeout(() => {
    //     next()
    //   }, 300)
    // }
  } else {
    // 多选情况
    if (!currentQuestion.value || currentQuestion.value.length == 0) {
      currentQuestion.value.push(item.value)
      currentQuestion.sort.push(item.sort)
      currentQuestion.option = item.id.toString()
    } else {
      // 多次选中
      if (!currentQuestion.value.includes(item.value)) {
        if (item.value == '以上全无' || currentQuestion.value.includes('以上全无')) {
          currentQuestion.value = []
          currentQuestion.value.push(item.value)
          currentQuestion.option = item.id.toString()
          currentQuestion.sort = []
          currentQuestion.sort.push(item.sort)
        } else {
          currentQuestion.value.push(item.value)
          currentQuestion.option = currentQuestion.option + ',' + item.id
          currentQuestion.sort.push(item.sort)
        }
      } else {
        currentQuestion.option = currentQuestion.option.replace(item.id + ',', '')
        currentQuestion.option = currentQuestion.option.replace(',' + item.id, '')
        currentQuestion.option = currentQuestion.option.replace(item.id, '')
        currentQuestion.value = currentQuestion.value.filter((val: string) => val != item.value)
        currentQuestion.sort = currentQuestion.sort.filter((val: string) => val != item.sort)
      }
    }
  }
}, 300)

const prev = () => {
  if (state.questionActive == 0) {
    state.tabActive--
    state.questionActive = state.questionList[state.tabActive].list.length - 1
  } else {
    state.questionActive--
  }
}
const next = () => {
  let canNext = true
  let isSpace = /^ *$/
  let current = state.questionList[state.tabActive].list[state.questionActive]
  // 当前版本取消风险跳转判断
  // if (current.exc && current.exc) {
  //   riskTest(current)
  // }
  if (
    current.value == '' &&
    isSpace.test(current.inputText) &&
    current.questionType != '搜索输入'
  ) {
    canNext = false
  }
  if (canNext) {
    // 下一题
    state.questionList = showCondition(originList.value)
    // console.log('新列表', state.questionList)
    if (
      state.tabActive + 1 == state.questionList.length &&
      state.questionActive + 1 == state.questionList[state.tabActive].list.length
    ) {
      // 提交问卷
      confirm()
    } else if (state.questionActive + 1 == state.questionList[state.tabActive].list.length) {
      state.tabActive++
      state.questionActive = 0
    } else {
      state.questionActive++
    }
  } else {
    uni.showToast({
      title: '请完成题目填写',
      icon: 'none'
    })
  }
}

const confirm = () => {
  const params = {
    clientId: 3,
    patientQuestionnaireAnswerVOs: []
  }
  state.questionList.forEach((item: any) => {
    item.list.forEach((val: any) => {
      const answerModel = {
        id: state.questionInfo.id,
        userId: userInfo.value.userId,
        empi: chooseInfo.value.empi,
        creator: '',
        createTime: state.questionInfo.createTime,
        updateTime: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        questionnaireId: state.questionInfo.questionnaireId,
        questionId: val.id,
        questionnaireRecordId: state.questionInfo.questionnaireId,
        optionId: '',
        content: '',
        extContent: val.questionType == '选择 + 输入' ? val.inputText : '',
        score: val.score
      }
      if (val.questionType == '单选' || val.questionType == '输入') {
        const answer = {
          ...answerModel,
          optionId: val.questionType == '单选' ? val.option : '',
          content: val.questionType == '输入' ? val.inputText : val.value
        }
        params.patientQuestionnaireAnswerVOs.push(answer)
      } else if (val.questionType == '多选') {
        const arr = val.option.split(',')
        if (val.value && val.value.length > 0) {
          val.value.forEach((i: string, idx: number) => {
            const answer = {
              ...answerModel,
              optionId: arr[idx],
              content: i
            }
            params.patientQuestionnaireAnswerVOs.push(answer)
          })
        } else {
          const answer = {
            ...answerModel,
            content: ''
          }
          params.patientQuestionnaireAnswerVOs.push(answer)
        }
      } else {
        if (val.value && val.value.length > 0) {
          val.value.forEach((v: any) => {
            const answer = {
              ...answerModel,
              content: v
            }
            params.patientQuestionnaireAnswerVOs.push(answer)
          })
        } else {
          const answer = {
            ...answerModel,
            content: ''
          }
          params.patientQuestionnaireAnswerVOs.push(answer)
        }
      }
    })
  })
  uni.showLoading({
    title: '正在提交问卷',
    mask: true
  })
  weight_save(params).then((res) => {
    if (res.code == 0) {
      let params = {
        userId: userInfo.value.userId,
        empi: userInfo.value.patientInfo.empi
      }
      base_info(params).then((res) => {
        userInfo.value.patientInfo = res.data
        userInfo.value.patientInfo.sportQuestionState = true
        store.commit('SET_USERINFO', userInfo.value)
        uni.hideLoading()
        uni.showToast({
          title: '问卷提交成功，正在评估结果。',
          icon: 'none',
          duration: 2000,
          success: () => {
            setTimeout(() => {
              if (
                store.state.CLIENTTYPE === 'checkAfterMini' &&
                !userInfo.value.patientInfo.reportState
              ) {
                uni.redirectTo({ url: '/packA/pages/questionaire/physical' })
              } else {
                if (userInfo.value.patientInfo.isSet) {
                  const params = {
                    empi: userInfo.value.patientInfo.empi,
                    date: parseTime(new Date().getTime() + 86400000, '{yyyy}-{mm}-{dd}')
                  }
                  hasSportsPlan(params).then((res) => {
                    if (res.data && res.data.length > 0) {
                      uni.redirectTo({ url: '/module/src/pages/sports/sportsPlan/index' })
                    } else {
                      uni.redirectTo({ url: '/module/src/pages/sports/sportsInfo/risk' })
                    }
                  })
                } else {
                  uni.redirectTo({ url: '/packA/pages/questionaire/risk' })
                }
              }
            }, 2000)
          }
        })
      })
    }
  })
}

// 搜索部分
const cancelSearch = () => {
  state.searchValue = ''
  state.searchFocus = false
  state.isSearch = false
  state.searchList = []
}
const clearSearchHistory = () => {
  state.searchHistory = []
  uni.removeStorageSync('searchHistory')
}
const searchFood = debounce((e) => {
  if (e == '') {
    state.isSearch = false
    state.searchList = []
    return
  }
  state.isSearch = true
  search_food(state.searchValue).then((res) => {
    state.searchList = res.data
    state.searchList.forEach((item) => {
      // 如果已选中的列表没有为false, 有就为true
      item.checked = false
      state.searchResults.forEach((i) => {
        if (i.dietName == item.dietName) {
          item.checked = true
        }
      })
    })
    // 保存搜索历史记录
    if (state.searchHistory.indexOf(e) == -1) {
      if (state.searchHistory.length >= 10) {
        state.searchHistory.pop()
      }
      state.searchHistory.unshift(e)
    }
    uni.setStorageSync('searchHistory', JSON.stringify(state.searchHistory))
  })
}, 1000)
const historySelect = (val: string) => {
  state.searchValue = val
  searchFood(state.searchValue)
}
const selectFoods = (item: any) => {
  if (!item.checked) {
    item.checked = true
    if (state.searchResults.includes(item.dietName)) {
      state.searchResults = state.searchResults.filter((name: string) => name != item.dietName)
    } else {
      state.searchResults.push(item.dietName)
    }
  } else {
    item.checked = false
    state.searchResults = state.searchResults.filter((name: string) => name != item.dietName)
  }
}
const removeFood = (item: string) => {
  state.searchResults = state.searchResults.filter((name: string) => name != item)
}
const searchConfirm = () => {
  searchShow.value = false
  state.searchValue = ''
  state.searchFocus = false
  state.isSearch = false
  state.searchList = []
  state.questionList[state.tabActive].list[state.questionActive].value = state.searchResults
}

const inputTest = (rule: any, val: any) => {
  // 输入类型题目判断
  switch (rule.operator) {
    case '填写完成':
      return val != ''
    case '=':
      return val == rule.value
    case '==':
      return val == rule.value
    case '===':
      return val === rule.value
    case '>':
      return val > rule.value
    case '<':
      return val < rule.value
    case '>=':
      return val >= rule.value
    case '<=':
      return val <= rule.value
    case '!=':
      return val != rule.value
  }
}

const riskTest = (val: any) => {
  // 风险类型判断
  switch (val.exc) {
    case 'special':
      if (val.option == 1) {
        uni.redirectTo({ url: '/module/src/pages/sports/sportsQuestionnaire/result?type=special' })
      }
      return
    case 'bloodsuger':
      if (Number(val.option) != 5) {
        uni.redirectTo({ url: '/module/src/pages/sports/sportsQuestionnaire/result?type=risk' })
      }
      return
    case 'bloodpressure':
      if (Number(val.option) != 10) {
        uni.redirectTo({ url: '/module/src/pages/sports/sportsQuestionnaire/result?type=risk' })
      }
      return
    case 'two-risk':
      if (val.option == 0) {
        uni.redirectTo({ url: '/module/src/pages/sports/sportsQuestionnaire/result?type=risk' })
      }
      return
    case 'pain':
      if (
        val.option != 0 &&
        state.questionList[state.tabActive].list.filter(
          (item: any) => item.exc && item.exc == 'knee-pain'
        )[0].option != 0
      ) {
        uni.redirectTo({ url: '/module/src/pages/sports/sportsQuestionnaire/result?type=risk' })
      }
      return
    case 'knee-pain':
      let isRisk = false
      let arr = state.questionList[state.tabActive].list.filter(
        (item: any) => item.exc && item.exc == 'pain'
      )
      arr.forEach((item: any) => {
        if (item.option != 0) {
          isRisk = true
        }
      })
      if (val.option != 0 && isRisk) {
        uni.redirectTo({ url: '/module/src/pages/sports/sportsQuestionnaire/result?type=risk' })
      }
      return
  }
}
const scroll = (e: any) => {
  oldScrollTop.value = e.target.scrollTop
}
const onChange = () => {
  console.log(listOld.value)
  //   state.questionList = showCondition(listOld.value)
  state.questionList = showCondition(originList.value)
}
</script>

<style lang="scss" scoped>
.body {
  min-height: calc(100vh - 120rpx - constant(safe-area-inset-bottom));
  min-height: calc(100vh - 120rpx - env(safe-area-inset-bottom));
  padding-bottom: calc(120rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
  .progress {
    padding: 24rpx 32rpx;
    background: #fff;
    .model-name {
      font-weight: 600;
      font-size: 40rpx;
      color: #222222;
      margin-bottom: 16rpx;
    }
  }
  .wrap {
    margin: 32rpx;
    padding: 32rpx;
    max-height: calc(100vh - 380rpx);
    background: #ffffff;
    border-radius: 16rpx;
    // overflow-y: scroll;
    .scroll-Y {
      position: relative;
      max-height: calc(100vh - 444rpx);
      overflow-y: scroll;
    }
    .tips {
      font-weight: 400;
      font-size: 28rpx;
      color: #999999;
    }
    .questionName {
      font-weight: 500;
      font-size: 36rpx;
      color: #222222;
      padding-top: 16rpx;
      .tag {
        display: inline-block;
        height: 40rpx;
        padding: 0 16rpx;
        margin-left: 8rpx;
        font-size: 24rpx;
        font-weight: 500;
        line-height: 40rpx;
        color: #fff;
        text-align: center;
        background: #5c8eff;
        border-radius: 4rpx;
        transform: translateY(-4rpx);
      }
    }
    .tips {
      font-weight: 400;
      font-size: 28rpx;
      color: #999999;
      margin-top: 8rpx;
    }
    .selects {
      margin-top: 32rpx;
      padding-bottom: 4rpx;
      border-top: 2rpx dashed #cfcfcf;
      border-spacing: 4rpx 4rpx;
    }
    .items {
      background: #fafafa;
      box-sizing: border-box;
      border-radius: 8rpx;
      font-weight: 400;
      font-size: 30rpx;
      color: #222222;
      padding: 24rpx 30rpx 22rpx;
      border: 1rpx solid transparent;
      margin-top: 32rpx;
      display: flex;
      justify-content: flex-start;
      .item-name {
        font-weight: 500;
        font-size: 32rpx;
        color: #222222;
      }
      .info-tag {
        display: inline-block;
        height: 48rpx;
        line-height: 48rpx;
        padding: 0 24rpx;
        margin-left: 32rpx;
        background: #ffffff;
        border-radius: 4rpx;
        border: 1rpx solid #e5e6eb;
        font-weight: 400;
        font-size: 24rpx;
        color: #666666;
        transform: rotateZ(360deg);
      }
    }
    .active {
      color: #00d1b6;
      background: rgba(0, 209, 182, 0.05);
      font-weight: 700;
      border: 1rpx solid #00d1b6;
      transform: rotateZ(360deg);
    }
    .type_input {
      height: 108rpx;
      line-height: 108rpx;
      border: none;
      border-bottom: 2rpx solid #222;
    }
    .search-input {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      width: 100%;
      height: 84rpx;
      padding: 22rpx 24rpx;
      margin-top: 24rpx;
      font-size: 30rpx;
      font-weight: 400;
      line-height: 84rpx;
      color: #999;
      background: #fff;
      border: 2rpx solid #000;
      border-radius: 48rpx;
    }

    .allergy-foods {
      height: 560rpx;
      margin-top: 24rpx;
      overflow: auto;

      .food-list {
        display: flex;
        flex-wrap: wrap;
        gap: 24rpx;
        justify-content: left;

        .foods-item {
          display: flex;
          align-items: center;
          height: 64rpx;
          padding: 0 16rpx;
          font-size: 28rpx;
          font-weight: 400;
          color: #00d1b6;
          background: rgb(0 209 182 / 10%);
          border-radius: 4rpx;
        }
      }
    }
  }

  .search-body {
    // 搜索弹窗
    width: 100vw;
    height: calc(100vh - 160rpx);

    .title {
      height: 108rpx;
      font-size: 32rpx;
      font-weight: 700;
      line-height: 108rpx;
      color: #222;
      text-align: center;
      border-bottom: 1rpx solid #e5e6eb;
    }

    .search-bar {
      padding: 24rpx 32rpx;
    }

    .search_content {
      // height: calc(100vh - 596rpx);
      background: #fff;

      .search_history {
        margin: 0 32rpx;

        .history_top {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20rpx;

          .title {
            font-size: 30rpx;
            font-weight: 700;
            color: #333;
          }

          .img_del {
            width: 40rpx;
            height: 40rpx;
            font-size: 40rpx;
            color: #999;
          }
        }

        .history_content {
          display: flex;
          flex-wrap: wrap;
          gap: 20rpx;
          justify-content: flex-start;

          .history_item {
            padding: 10rpx 30rpx;
            font-size: 26rpx;
            font-weight: 400;
            color: #666;
            background: #fafafa;
            border-radius: 30rpx;
          }
        }
      }

      .nodata {
        text-align: center;

        .img_nodata {
          width: 320rpx;
          height: 240rpx;
          margin-top: 222rpx;
        }

        .nodata_text {
          font-size: 28rpx;
          font-weight: 400;
          color: #666;
        }
      }
      .scroll_view_style {
        height: calc(100vh - 524rpx);
        overflow: auto;
      }
      .search_list {
        background: #fff;

        .search_item {
          position: relative;
          box-sizing: border-box;
          height: 108rpx;
          padding: 34rpx 32rpx;
          border-bottom: 1rpx solid #e5e6eb;

          .name {
            font-size: 30rpx;
            font-weight: 500;
            color: #222;
          }

          .img_right {
            position: absolute;
            top: 50%;
            right: 32rpx;
            width: 40rpx;
            height: 40rpx;
            margin-top: -20rpx;
          }
        }
      }
    }

    .popbtn {
      width: 100%;
    }
  }

  .fixed {
    position: fixed;
    width: 100%;
    bottom: 0;
    left: 0;
    z-index: 10;
    padding: 24rpx 32rpx;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    box-sizing: border-box;
    background: #ffffff;
    display: flex;
    justify-content: space-between;
    gap: 24rpx;
    .pre_btn {
      background: #ffffff;
      width: 100%;
      border-radius: 44rpx;
      font-weight: 500;
      font-size: 32rpx;
      border: 1rpx solid #00d1b6;
      color: #00d1b6;
    }
    .next_btn {
      width: 100%;
      background: #00d1b6;
      border-radius: 44rpx;
      font-weight: 500;
      font-size: 32rpx;
      color: #ffffff;
    }
  }
  ::v-deep .u-modal__title {
    font-weight: 500 !important;
    font-size: 34rpx !important;
    color: #222222 !important;
  }
}

:v-deep .u-search {
  padding: 10px;
}

::v-deep .u-search__content__input--placeholder {
  font-size: 30rpx !important;
  color: #999 !important;
}

::v-deep .u-search__content {
  justify-content: flex-start;
  height: 80rpx !important;
  padding: 20rpx 24rpx !important;
  background-color: #fff !important;
  border: 2rpx solid #000;
  border-radius: 40rpx !important;
  border-color: #000 !important;
}

::v-deep .u-search__content__icon {
  padding: 0 !important;

  .u-icon .u-icon__icon {
    color: #000 !important;
  }
}

::v-deep .u-search__content__input {
  font-size: 30rpx !important;
  background-color: #fff !important;
}

::v-deep .u-search__action {
  font-size: 30rpx !important;
  font-weight: 500;
  line-height: 80rpx !important;
  color: #00d1b6 !important;
}

::v-deep .u-icon__icon {
  font-size: 44rpx !important;
  line-height: 50rpx !important;
}
</style>
